<template>
  <div class="wash-pricing">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>价格设置</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加价格
          </el-button>
        </div>
      </template>
      
      <el-table :data="pricingList" v-loading="loading" border>
        <el-table-column prop="service" label="服务名称" />
        <el-table-column prop="category" label="分类" />
        <el-table-column prop="basePrice" label="基础价格">
          <template #default="{ row }">
            ¥{{ row.basePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="urgentPrice" label="加急价格">
          <template #default="{ row }">
            ¥{{ row.urgentPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleToggleStatus(row)">
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" style="color: #f56c6c;" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 价格编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '添加价格' : '编辑价格'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="服务名称" prop="service">
          <el-input v-model="formData.service" placeholder="请输入服务名称" />
        </el-form-item>
        <el-form-item label="服务分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%;">
            <el-option label="干洗" value="dry_clean" />
            <el-option label="水洗" value="water_wash" />
            <el-option label="熨烫" value="ironing" />
            <el-option label="修补" value="repair" />
            <el-option label="染色" value="dyeing" />
          </el-select>
        </el-form-item>
        <el-form-item label="基础价格" prop="basePrice">
          <el-input-number v-model="formData.basePrice" :min="0" :precision="2" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="加急价格" prop="urgentPrice">
          <el-input-number v-model="formData.urgentPrice" :min="0" :precision="2" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { pricing } from '@/api/wash/index'

const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('create')
const formRef = ref()
const pricingList = ref([])

// 分页
const page = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 表单数据
const formData = reactive({
  id: '',
  service: '',
  category: '',
  basePrice: 0,
  urgentPrice: 0,
  status: 'active',
  remark: ''
})

// 表单验证规则
const formRules = {
  service: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择服务分类', trigger: 'change' }],
  basePrice: [{ required: true, message: '请输入基础价格', trigger: 'blur' }],
  urgentPrice: [{ required: true, message: '请输入加急价格', trigger: 'blur' }]
}

const getPricingList = async () => {
  loading.value = true
  try {
    const res = await getPricingListAPI({
      page: page.current,
      size: page.size
    })
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      pricingList.value = data.records || data.content || data || []
      page.total = data.total || data.totalElements || 0
    } else {
      pricingList.value = []
      page.total = 0
    }
  } catch (error) {
    console.error('获取价格列表失败:', error)
    ElMessage.warning('获取价格列表失败，请检查网络连接')
    pricingList.value = []
    page.total = 0
  } finally {
    loading.value = false
  }
}

const handleAdd = () => {
  dialogType.value = 'create'
  resetFormData()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该价格设置吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deletePricing(row.id)
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success('删除成功')
      getPricingList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    const res = await updatePricing(row.id, { ...row, status: newStatus })
    if (res && (res.code === 200 || res.success)) {
      row.status = newStatus
      ElMessage.success(`${newStatus === 'active' ? '启用' : '禁用'}成功`)
    }
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    let res
    if (dialogType.value === 'create') {
      res = await createPricing(formData)
    } else {
      res = await updatePricing(formData.id, formData)
    }
    
    if (res && (res.code === 200 || res.success)) {
      ElMessage.success(dialogType.value === 'create' ? '添加成功' : '更新成功')
      dialogVisible.value = false
      getPricingList()
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const resetFormData = () => {
  Object.assign(formData, {
    id: '',
    service: '',
    category: '',
    basePrice: 0,
    urgentPrice: 0,
    status: 'active',
    remark: ''
  })
}

const handleSizeChange = () => {
  getPricingList()
}

const handleCurrentChange = () => {
  getPricingList()
}

onMounted(() => {
  getPricingList()
})
</script>

<style lang="scss" scoped>
.wash-pricing {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style> 